// pages/category/category.js
const storeService = require('../../../../api/storeService.js')
const productService = require('../../../../api/productService.js')
const shopcartService = require('../../../../api/shopcartService.js')
const memberService = require('../../../../api/memberService.js')

const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    storeId: '',
    store: '',
    category: [], // 类目以及类目下商品
    tabSelected: '0',
    goodsList: [],
    scrollList: [],
    device: {},
    maxNum: 0,
    scrollTop: 0,
    isScrollTo: false,
    loading: true,
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
    overlayStyle: 'background: rgba(255, 255, 255, 0.9)',
    showTabbar: true,
    phone: false
  },
  // 前往首页
  toHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 获取当前门店的所有分类和商品
  getMenuProduct: function (storeId) {
    const that = this
    console.log(storeId)
    productService.getMenuProduct(storeId, "RETAIL").then(res => {
      wx.hideLoading()
      console.log(res)
      let selected = this.data.tabSelected
      let tempArray = []
      if (res != '') {
        tempArray = res[selected].products
        let tempGoodsList = []
        res.forEach(item => {
          var tempData = that.productsSort(item.products)
          let tempList = []
          tempData.forEach(data => {
            let produtlabel = []
            let promotions = []
            let specifications = null
            if (data.labels && data.labels.length > 0) {
              data.labels.forEach(ele => {
                if (ele.type === 'GOODSLABEL') {
                  produtlabel.push(ele)
                } else if (ele.type === 'PROMOTIONLABEL') {
                  promotions.push(ele)
                }
              })
            }
            if (data.productProperties && data.productProperties.length > 0) {
              for (let i = 0; i < data.productProperties.length; i++) {
                const ele = data.productProperties[i];
                if (ele.propertyName === '规格') {
                  specifications = ele.propertyValue
                  break
                } else {}
              }
            }
            let tempItem = {
              ...data,
              produtlabel: produtlabel,
              promotions: promotions,
              specifications: specifications ? specifications : ''
            }
            tempList.push(tempItem)
          })
          tempGoodsList.push(tempList)
        })
        wx.hideToast()
        that.setData({
          category: res,
          goodsList: tempGoodsList
        })
        that.setData({
          loading: false
        })
        var query = wx.createSelectorQuery();
        setTimeout(() => {
          query.selectAll('.goods-content').boundingClientRect()
          query.exec(function (res) {
            //res就是 所有标签为mjltest的元素的信息 的数组
            console.log(res)
            that.setData({
              scrollList: res[0]
            })
            try {
              var device = wx.getSystemInfoSync()
              var tempHeight = 0
              var num = res[0].length
              for (let index = res[0].length - 1; index > 0; index--) {
                const ele = res[0][index];
                if (tempHeight < device.windowHeight) {
                  tempHeight = tempHeight + ele.height
                  num = index
                }
              }
              that.setData({
                maxNum: num,
                device: device
              })
            } catch (e) {
              // Do something when catch error
            }
          })
        }, 100);
      } else {
        this.setData({
          category: res,
          goodsList: tempArray
        })
        that.setData({
          loading: false
        })
      }
    })
  },
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  getLocation: function () {
    const self = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        try {
          var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
          if (tempAllStores) {
            // Do something with return value
            let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
            app.globalData.storeInfo = tempAllStores[tempIndex];
            // 获取当前门店的所有分类和商品
            self.getMenuProduct(tempAllStores[tempIndex].id)
          } else {
            // 查询所有门店
            storeService.queryList().then(res => {
              var allStores = [];
              res.forEach(item => {
                if (item.status === 'OPEN') {
                  allStores.push(item)
                }
              });
              try {
                wx.setStorageSync('wj_allStores', allStores)
              } catch (e) {
                console.log(e)
              }
              let tempIndex = self.getNearestStore(allStores, latitude, longitude);
              return allStores[tempIndex]
            }).then(res => {
              app.globalData.storeInfo = res;
              self.getMenuProduct(res.id)
            })
          }
        } catch (e) {
          // Do something when catch error
        }
      },
      fail: function (res) {
        console.log(res)
        self.setData({
          hasaAuthorization: false
        })
        wx.hideTabBar()
      }
    })
  },
  // 跳转到商品详情页面
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?productId=' + val.currentTarget.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  // 类目点击事件
  clickCategory: function (e) {
    this.setData({
      tabSelected: e.currentTarget.dataset.idx,
      isScrollTo: true
    })
    const that = this
    //创建节点选择器
    const idx = e.currentTarget.dataset.idx
    const scrollList = that.data.scrollList
    wx.pageScrollTo({
      scrollTop: scrollList[idx].top - scrollList[0].top,
      duration: 0
    })
  },
  /**
   * 监听页面滚动
   */
  onPageScroll: function (e) {
    const that = this
    const scrollList = that.data.scrollList
    const isScrollTo = that.data.isScrollTo
    let scrollTop = e.scrollTop
    let idx = that.data.tabSelected
    let num = that.data.maxNum
    if (isScrollTo) {
      //栏目跳转
      that.setData({
        isScrollTo: false
      })
    } else {
      //正常滚动
      for (let index = 0; index < scrollList.length; index++) {
        const ele = scrollList[index];
        let minHeight = ele.top - scrollList[0].top
        let maxHeight = scrollList[index].top + scrollList[index].height - scrollList[0].top
        if (scrollTop >= minHeight && scrollTop < maxHeight) {
          idx = index
          if (idx !== that.data.tabSelected) {
            that.setData({
              tabSelected: idx,
              isScrollTo: false
            })
          }
        }
      }
    }
  },
  // 加入购物车
  addShopcart: function (val) {
    console.log(val)
    var productId = val.currentTarget.dataset.id;
    let business = val.currentTarget.dataset.business;
    let storeId = ''
    let loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus) {
      if (business === "DISTRIBUTION") {
        try {
          var data = wx.getStorageSync('wj_distributionStore')
          if (data) {
            storeId = data.id
          }
        } catch (e) {}
      } else {
        storeId = app.globalData.storeInfo.id
      }
      var postData = {
        storeId: storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      //storeId = app.globalData.storeInfo.id
      var balance = 0
      console.log(storeId, productId)
      productService.getDetails(storeId, productId).then(res => {
        console.log(res)
        if (res) {
          balance = res.balance
          if (balance === 0 || balance === null || balance === '') {
            wx.showToast({
              title: '门店中该商品库存不足，请选购其他商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            console.log(postData)
            shopcartService.cateringAdd(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '添加购物袋成功~',
                icon: 'none',
                duration: 2000
              })
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          wx.showToast({
            title: '添加购物袋失败~',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请登陆后再添加购物袋哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 查询商品库存
  queryGoodsInventory: function (productId) {
    let storeId = app.globalData.storeInfo.id
    var balance = 0
    productService.getDetails(storeId, productId).then(res => {
      balance = res.balance
    })
    set
    return balance
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    try {
      if (!app.globalData.userInfo) {
        return false;
      } else {
        return true;
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 上拉
  bindscrolltolower: function (e) {
    console.log("111111")
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.editTabbar();
    const self = this;
    // 查询统配门店信息
    storeService.getDistributionStore().then(res => {
      console.log(res)
      if (res) {
        var distributionStore = res;
        try {
          wx.setStorageSync('wj_distributionStore', distributionStore)
        } catch (e) {
          console.log(e)
        }
      }
    }).catch(e => {

    })
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      this.setData({
        store: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
      this.getMenuProduct(this.data.storeId)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      self.getLocation()
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      try {
        wx.setStorageSync('wj_sharingId', scene)
      } catch (e) {}
    }
    if (this.options.mobile && this.options.mobile != '' && this.options.mobile != undefined) {
      const mobile = this.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getMenuProduct(app.globalData.storeInfo.id)
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/category/category?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/category/category',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
        }
      }
    }
  },
  addShopcartTest: function (val) {

  },
  bindsubmit: function (val) {
    console.log(val.detail)
    const that = this
    var productId = val.detail.target.dataset.id;
    let business = val.detail.target.dataset.business;
    let storeId = ''
    let loginStatus = this.checkAuth()
    let balance = val.detail.target.dataset.balance;
    console.log(loginStatus)
    if (loginStatus) {
      if (business === "DISTRIBUTION") {
        try {
          var data = wx.getStorageSync('wj_distributionStore')
          if (data) {
            storeId = data.id
          }
        } catch (e) {}
      } else {
        storeId = app.globalData.storeInfo.id
      }
      var postData = {
        storeId: storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      if (business === 'DISTRIBUTION') {
        balance = 0
        console.log(storeId, productId)
        productService.getDetails(storeId, productId).then(res => {
          console.log(res)
          balance = res.balance
          addShopcart(balance)
        })
      } else {
        addShopcart(balance)
      }

      function addShopcart(balance) {
        if (app.globalData.userInfo.member) {
          if (balance === 0 || balance === null || balance === '') {
            wx.showToast({
              title: '门店中该商品库存不足，请选购其他商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            try {
              wx.setStorageSync('wj_wxa_formId', val.detail.formId)
            } catch (e) {}
            shopcartService.cateringAdd(postData).then(res => {
              console.log(res)
              wx.showToast({
                title: '添加购物袋成功~',
                icon: 'none',
                duration: 2000
              })
            }).catch(err => {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          that.handlePopupPhone()
          // wx.showToast({
          //   title: '请先绑定手机号码后再添加哦~',
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    } else {
      wx.showToast({
        title: '请先点击头像授权登录后添加哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  recorderPopup: function () {
    this.toggleBottomPopup()
  },
  /**
   * 打开分享弹窗
   */
  toggleBottomPopup() {
    this.toggle('middle');
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`overlayStyle`]: this.data.overlayStyle
    });
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})